<?php
/**
 * Created by PhpStorm.
 * User: zhengzifan
 * Date: 2017/3/16
 * Time: 11:05
 */

namespace app\admin\controller;
use think\Loader;

class CarsController extends CommonController{

    public $model;
    public $businesses_id;
    public $TableColumnNameArr = [
        '编号' => 'name',
        '车辆名称' => 'name',
        '车牌号' => 'plate_no',
        '发动机编号' => 'engine_no',
        '车架号码' => 'vin_no',
        '车辆型号' => 'car_mode_name',
        '所属网点' => 'store_id',
        '状态' => 'state',
        '用途' => 'purpose_id',
        '出厂日期' => 'product_date',
        '年审日期' => 'trial_date',
        '车属单位' => 'unit_name',
        '所属供应商' => 'supplier_id',
        '租赁类型' => 'hire_mode',
        '租赁时长' => 'hire_timelen',
        '是否含保险' => 'has_insurance',
        '保险项目' => 'insurance_id',
        '付款方式' => 'pay_mode',
        '付款时长' => 'pay_timelen',
        '提车日期' => 'get_time',
        '起租日期' => 'start_hiretime',
        '终止日期' => 'end_hiretime',
        '其他说明' => 'other_remark',
        '合同上传' => 'contract_files',
        '证件上传' => 'cert_files'
    ];
    public $hire_timelens;
    public $pay_modes;
    public $pay_timelens;
    public $car_modes;
    public $hire_modes;
    public $states;
    public $purposes;
    public $stores;

    /**
     * 初始化adminModel
     */
    public function _initialize(){
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = model('Cars');
        
        $this->hire_timelens = config('HIRE_TIMELEN');
        $this->pay_modes = config('PAY_MODES');
        $this->pay_timelens = config('PAY_TIMELEN');
        $this->car_modes = db('CarConfig')->where(['config_mode'=>1])->select();
        $this->hire_modes = db('CarConfig')->where(['config_mode'=>2])->select();
        $this->states = db('CarConfig')->where(['config_mode'=>0])->select();
        $this->purposes = db('CarConfig')->where(['config_mode'=>3])->select();
        $this->stores = db('Store')->where(['id'=>['>','0']])->select();
        $store_ids = model('AdminStore')->where(['admin_id'=>session('admin')['id']])->column('store_id');
        if(!empty($store_ids) && count($store_ids)>0){
            $this->stores = db('Store')->where(['id'=>['in',$store_ids]])->select();
        }
        $this->businesses_id = 0;
        if(!empty(session('admin')['businesses_id']) && session('admin')['businesses_id'] > 0){
            $this->businesses_id = session('admin')['businesses_id'];
        }
        $businesses = db('businesses')->select();
        $this->assign([
            'hire_timelens'=>$this->hire_timelens,
            'pay_modes'=>$this->pay_modes,
            'pay_timelens'=>$this->pay_timelens,
            'car_modes'=>$this->car_modes,
            'purposes'=>$this->purposes,
            'hire_modes'=>$this->hire_modes,
            'states'=>$this->states,
            'stores'=>$this->stores,
            'businesses_id' => $this->businesses_id,
            'businesses' => $businesses
        ]);
    }

    /**
     * 列表页
     */
    public function index(){
        $car_mode_name = input('param.car_mode_name');
        $hire_mode = input('param.hire_mode');
        $state = input('param.state');
        $store_id = input('param.store_id');
        $purpose_id = input('param.purpose_id');
        $purpose = input('param.purpose');
        $where['a.id'] = ['>',0];
        $store_ids = model('AdminStore')->where(['admin_id'=>session('admin')['id']])->column('store_id');
        if(!empty($store_ids) && count($store_ids)>0){
            $where['a.store_id'] = ['in',$store_ids];
        }
        if($car_mode_name && $car_mode_name>0){
            $where['a.car_mode_name'] = $car_mode_name;
        }
        if($hire_mode && $hire_mode>0){
            $where['a.hire_mode'] = $hire_mode;
        }
        if($state && $state>0){
            $where['a.state'] = $state;
        }
        if($store_id && $store_id>0){
            $where['a.store_id'] = $store_id;
        }
        if($purpose_id && $purpose_id>0){
            $where['a.purpose_id'] = $purpose_id;
        }
        if($purpose){
            $where['a.name|a.plate_no|a.engine_no|a.vin_no|a.unit_name|a.purpose|a.contactor'] = ['like','%'.$purpose.'%'];
        }
        if($this->businesses_id > 0){
            $where['a.businesses_id'] = $this->businesses_id;
        }
        $list = $this->model->where($where)
            ->alias('a')
            ->join('__CAR_CONFIG__ hc','hc.id=a.hire_mode and hc.config_mode=2','LEFT')
            ->join('__CAR_CONFIG__ st','st.id=a.state and st.config_mode=0','LEFT')
            ->join('__CAR_CONFIG__ pp','pp.id=a.purpose_id and pp.config_mode=3','LEFT')
            ->join('__STORE__ ss','ss.id=a.store_id','LEFT')
            ->join('__SUPPLIERS__ sp','sp.id=a.supplier_id','LEFT')
            ->join('__CAR_RULES__ cr','cr.car_id = a.id and cr.hire_mode = a.hire_mode and cr.hire_timelen = a.hire_timelen and cr.sale_mode=0','LEFT')
            ->field('a.*,cr.deposit_price as deposit_price,cr.hire_price as hire_price,cr.total_amount as total_amount,sp.nickname as supplier_name,hc.config_name as hire_mode_name,ss.name as store_name,st.config_name as state_name,pp.config_name as purpose_name')
            ->order('create_time desc')
            ->paginate(20,false,['query' => request()->param()]);
        $page = $list->render();
        
        $this->assign([
            'car_mode_name'=>$car_mode_name,
            'hire_mode'=>$hire_mode,
            'state'=>$state,
            'store_id'=>$store_id,
            'purpose_id'=>$purpose_id,
            'purpose'=>$purpose,
            'list'=>$list,
            'page'=>$page
        ]);
        return $this->fetch('index');
    }

    /**
     * 新增与修改
     */
    public function info(){
        $img_ext_list =  ['jpg', 'png', 'gif', 'jpeg'];
        $post_id = input('param.id');
        $get_id = input('param.id');
        $info = $this->model->where(['a.id'=>$get_id])
        ->alias('a')
        ->join('__CAR_RULES__ cr','cr.car_id = a.id and cr.hire_mode = a.hire_mode and cr.hire_timelen = a.hire_timelen and cr.sale_mode=0','LEFT')            
        ->field('a.*,cr.deposit_price as deposit_price,cr.hire_price as hire_price,cr.total_amount as total_amount,cr.amount as amount')
        ->find();
        $customer=db('Customer')->where(['id'=>['>','0']])->select();
        $suppliers=db('Suppliers')->where(['id'=>['>','0']])->select();
        $insurances = db('Insurance')->where(['id'=>['>','0']])->select();
        $trial_date = time();
        $product_date = time();
        $next_paytime = time();
        $get_time = time();
        $start_hiretime = time();
        $end_hiretime = time();
        $car_id = 0;
        if($info){
            $trial_date = $info['trial_date'];
            $product_date = $info['product_date'];
            $next_paytime = $info['next_paytime'];
            $get_time = empty($info['get_time']) ? time() : $info['get_time'];
            $start_hiretime = empty($info['start_hiretime']) ? time() : $info['start_hiretime'];
            $end_hiretime = empty($info['end_hiretime']) ? time() : $info['end_hiretime'];
            $car_id = $info['id'];
        }
        $fileArrList = array();
        $contractFileArrList = array();
        $certFileArrList = array();
        $contractFileArr = array();
        $certFileArr = array();
        $insuranceArr = array();
        $contractFileList = db('CarFile')->where(['car_id'=>$car_id])->select();
        $carInsuranceList = db('CarInsurance')->where(['car_id'=>$car_id])->select();
        foreach($contractFileList as $item){
            $fileArr = $item;
            $fileArrList[] = $item['file_url'];
            if($item['file_mode'] == 0){
                $contractFileArrList[] = $item;
                $contractFileArr[] = $item['file_url'];
            }else{
                $certFileArrList[] = $item;
                $certFileArr[] = $item['file_url'];
            }
        }
        foreach($carInsuranceList as $item){
            $insuranceArr[] = $item['insurance_id'];
        }
        
        if(IS_POST){
            $data = input('param.');
            if($data['product_date']){
			    $data['product_date'] = strtotime($data['product_date']);
            }
            if($data['trial_date']){
			    $data['trial_date'] = strtotime($data['trial_date']);
            }
            if($data['get_time']){
			    $data['get_time'] = strtotime($data['get_time']);
            }
            if($data['next_paytime']){
			    $data['next_paytime'] = strtotime($data['next_paytime']);
            }
            if($data['start_hiretime']){
			    $data['start_hiretime'] = strtotime($data['start_hiretime']);
            }
            if($data['end_hiretime']){
			    $data['end_hiretime'] = strtotime($data['end_hiretime']);
            }
            $data['customer_id'] = 0; 
            $data['update_time'] = time(); 
            $car_insurances = isset($data['insurance_id'])?$data['insurance_id']:[];
            $contract_files = isset($data['contract_files'])?$data['contract_files']:[];
            $cert_files = isset($data['cert_files'])?$data['cert_files']:[];
            $data['insurance_id'] = 0;
            $car_mode_info = db('CarConfig')->where(['config_mode'=>1,'config_name'=>$data['car_mode_name']])->find();
            if(empty($car_mode_info) && count($car_mode_info)<=0){
                if($car_mode = db('CarConfig')->insert([
                    'config_mode' => 1,
                    'parent_id' => 0,
                    'config_value' => 0,
                    'config_name' => $data['car_mode_name'],
                    'create_id' => session('admin')['id'],
                    'create_time' => time(),
                    'remark' => $data['car_mode_name'],
                    'businesses_id' => $this->businesses_id
                ],true,true)){
                    $data['car_mode'] = $car_mode;
                }
            }else{
                $data['car_mode'] = $car_mode_info['id'];
            }
            unset($data['deposit_price']);
            unset($data['hire_price']);
            unset($data['total_amount']);
            if($post_id && $post_id>0){
                if($this->model->isUpdate(true)->save($data)){
                    $this->saveInsurances($post_id,$car_insurances,$insuranceArr);
                    $this->saveFileCar($post_id,$contract_files,$cert_files,$fileArrList);
					admin_log("编辑车辆信息，ID：$post_id");
					$this->redirect('Cars/index');
                    return;
                }else{
                    $this->error($this->model->getError());
                }
            }else{
                //新增操作
			    $data['creator_id'] = session('admin')['id'];
                $data['create_time'] = time();
                $data['name'] = $data['plate_no'];
                if($this->model->save($data)){
                    $name = date('Ymd',time()).'-'.$this->model->id;
                    $this->model->where(['id'=>$this->model->id])->update(['name'=>$name]);
                    $this->saveInsurances($this->model->id,$car_insurances,$insuranceArr);
                    $this->saveFileCar($this->model->id,$contract_files,$cert_files,$fileArrList);
					admin_log("新增车辆信息，ID：".$this->model->id);
                    $this->redirect('Cars/index');
                    return;
                }else{
                    $this->error($this->model->getError());
                }
            }
        }
        $this->assign([
            'customer' => $customer,
            'suppliers' => $suppliers,
            'insurances' => $insurances,
            'info' => $info,
            'trial_date' => $trial_date,
            'product_date' => $product_date,
            'get_time' => $get_time,
            'next_paytime' => $next_paytime,
            'start_hiretime' => $start_hiretime,
            'end_hiretime' => $end_hiretime,
            'img_ext_list'=>$img_ext_list,
            'cert_file_list'=>$certFileArrList,
            'contract_file_list'=>$contractFileArrList,
            'insuranceArr'=>$insuranceArr
        ]);
        return $this->fetch('info');
    }

    /**
     * 保存保险信息
    */
    protected function saveInsurances($car_id,$car_insurances,$insuranceArr){
        $insuranceInsertArr = [];
        if(!empty($car_insurances) && count($car_insurances)>0){
            foreach($car_insurances as $item){
                if(!empty($item) && strlen($item)>0){
                    if(!in_array($item,$insuranceArr)){
                        $insuranceInsertArr[] = [
                            'car_id' => $car_id,
                            'insurance_id' => $item
                        ];
                    }
                }
            }
        }
        if(!empty($insuranceArr) && count($insuranceArr)>0){
            foreach($insuranceArr as $item){
                if(!empty($item) && strlen($item)>0){
                    if(!in_array($item,$car_insurances)){
                        db('CarInsurance')->where(['car_id'=>$car_id,'insurance_id'=>$item])->delete();
                    }
                }
            }
        }

        if(!empty($insuranceInsertArr) && count($insuranceInsertArr)>0){
            db('CarInsurance')->insertAll($insuranceInsertArr);
        }
    }

    /**
     * 保存附件信息
    */
    protected function saveFileCar($car_id,$contract_files,$cert_files,$fileArrList){
        $ip = $this->request->ip();
        $fileArrSelect = array();
        $fileArrInsert = array();
        
        //新增资料
        foreach($contract_files as $item){
            $fileArrSelect[] = $item;
            if(empty($fileArrList) || count($fileArrList)<=0 || !in_array($item,$fileArrList)){
                if($item){
                    $file_ext = '';
                    $file_arr = explode('.',$item);
                    if(count($file_arr)>1){
                        $file_ext = $file_arr[count($file_arr)-1];
                    }
                    $fileArrInsert[] = [
                        'file_name' => $item,
                        'file_url' => $item,
                        'car_id' => $car_id,
                        'creator_id' => session('admin')['id'],
                        'create_time' => time(),
                        'file_mode' => 0,
                        'file_ext' => $file_ext,
                        'ip' => $ip
                    ];
                }
            }
        }
        //新增资料
        foreach($cert_files as $item){
            $fileArrSelect[] = $item;
            if(empty($fileArrList) || count($fileArrList)<=0 || !in_array($item,$fileArrList)){
                if($item){
                    $file_ext = '';
                    $file_arr = explode('.',$item);
                    if(count($file_arr)>1){
                        $file_ext = $file_arr[count($file_arr)-1];
                    }
                    $fileArrInsert[] = [
                        'file_name' => $item,
                        'file_url' => $item,
                        'car_id' => $car_id,
                        'creator_id' => session('admin')['id'],
                        'create_time' => time(),
                        'file_mode' => 1,
                        'file_ext' => $file_ext,
                        'ip' => $ip
                    ];
                }
            }
        }
        if(!empty($fileArrInsert) && count($fileArrInsert)>0){
            model('CarFile')->saveAll($fileArrInsert);
        }
        if($fileArrList && count($fileArrList)>0){
            //删除资料
            foreach($fileArrList as $item){
                if(!in_array($item,$fileArrSelect)){
                    model('CarFile')->where(['car_id'=>$car_id,'file_url'=>$item])->delete();
                }
            }
        }
    }

    /**
     * 删除
     */
    public function del(){
        $get_id = input('param.id');
        if($this->model->where(['id'=>$get_id])->delete()){
            db('CarFile')->where(['car_id'=>$get_id])->delete();
            admin_log("删除车辆，ID：$get_id");
            $this->redirect('Cars/index');
        }else{
            getAlert('操作失败！');
        }
    }

    /*
     * 导入Excel
    */
    public function import_data(){
        $ccModel = model('CarConfig');
        $stModel = model('Store');
        $ssModel = model('Suppliers');
        $csModel = model('Customer');
        $inModel = model('Insurance');
        $json = [
            'status' => 0,
            'msg' => '请选择导入数据文件'
        ];
        if(IS_POST){
            $file_urls = input('file_url');
            if(!empty($file_urls) && count($file_urls)>0){
                Loader::import('PHPExcel.PHPExcel');
                Loader::import('PHPExcel.PHPExcel.PHPExcel_IOFactory');
                Loader::import('PHPExcel.PHPExcel.PHPExcel_Cell');
                //实例化PHPExcel
                $customers = $csModel->where(['id'=>['>','0']])->select();
                $suppliers = $ssModel->where(['id'=>['>','0']])->select();
                $insurances = $inModel->where(['id'=>['>','0']])->select();
                foreach($file_urls as $path){
                    $path = ROOT_PATH.$path;
                    $re = actionRead($path, 'utf-8');
                    $imgs = extractImageFromWorksheet($path);
                    
                    array_splice($re, 1, 0);
                    $columnNameArr = [];
                    if(empty($re) || count($re)<=0){
                        $json['msg'] = '文件不存在任何数据';
                        echo json_encode($json);
                        exit;
                    }
                    foreach($re[0] as $item){
                        if(!empty($item) && $item !== ''){
                            $columnNameArr[] = $item;    
                        }
                    }
                    if(empty($columnNameArr) || count($columnNameArr)<=0){
                        $json['msg'] = '文件不存在任何数据';
                        echo json_encode($json);
                        exit;
                    }
    
                    /*将数组的键改为自定义名称*/
                    $list = [];
                    unset($re[0]);
                    $ind = 2;
                    foreach($re as $row){
                        $item = [];
                        for($i = 0;$i < count($columnNameArr);$i++){
                            $key = $columnNameArr[$i];
                            $value = $this->TableColumnNameArr[$key];
                            $item_id = 0;
                            if($value == 'car_mode_name'){
                                $item['car_mode'] = 0;
                                $enum_item = searchArray($this->car_modes,'config_name',$row[$i]);
                                $item[$value] = $row[$i];
                                if($enum_item['id'] == 0){
                                    $m_cc = [
                                        'parent_id' => 0,
                                        'config_mode' => 1,
                                        'config_value' => 0,
                                        'config_name' => $row[$i],
                                        'creator_id' => session('admin')['id'],
                                        'create_time' => time(),
                                        'remark' => $row[$i]
                                    ];
                                    if($car_mode_id = $ccModel->save($m_cc)){
                                        $item[$value] = $car_mode_id;
                                    }
                                }
                                continue;
                            }else if($value == 'store_id'){
                                $enum_item = searchArray($this->stores,'name',$row[$i]);
                                $item[$value] = $enum_item['id'];
                                if($enum_item['id'] == 0){
                                    $m_st = [
                                        'name' => $row[$i],
                                        'store_no' => $row[$i],
                                        'contactor' => $row[$i],
                                        'tel' => $row[$i],
                                        'creator_id' => session('admin')['id'],
                                        'create_time' => time()
                                    ];
                                    if($st_id = $stModel->insert($m_st,true,true)){
                                        $item[$value] = $st_id;
                                        $this->stores = $stModel->where(['id'=>['>','0']])->select();
                                    }
                                }
                                continue;
                            }else if($value == 'state'){
                                $enum_item = searchArray($this->states,'config_name',$row[$i]);
                                $item[$value] = $enum_item['id'];
                                if($enum_item['id'] == 0){
                                    $m_ss = [
                                        'parent_id' => 0,
                                        'config_mode' => 0,
                                        'config_value' => 0,
                                        'config_name' => $row[$i],
                                        'creator_id' => session('admin')['id'],
                                        'create_time' => time(),
                                        'remark' => $row[$i]
                                    ];
                                    if($state_id = $ccModel->insert($m_ss,true,true)){
                                        $item[$value] = $state_id;
                                        $this->states = db('CarConfig')->where(['config_mode'=>0])->select();
                                    }
                                }
                                continue;
                            }else if($value == 'purpose_id'){
                                $enum_item = searchArray($this->purposes,'config_name',$row[$i]);
                                $item[$value] = $enum_item['id'];
                                if($enum_item['id'] == 0){
                                    $m_pp = [
                                        'parent_id' => 0,
                                        'config_mode' => 3,
                                        'config_value' => 0,
                                        'config_name' => $row[$i],
                                        'creator_id' => session('admin')['id'],
                                        'create_time' => time(),
                                        'remark' => $row[$i]
                                    ];
                                    if($pp_id = $ccModel->insert($m_pp,true,true)){
                                        $item[$value] = $pp_id;
                                        $this->purposes = db('CarConfig')->where(['config_mode'=>3])->select();
                                    }
                                }
                                continue;
                            }else if($value == 'supplier_id'){
                                $enum_item = searchArray($suppliers,'name',$row[$i]);
                                $item[$value] = $enum_item['id'];
                                if($enum_item['id']>0){
                                    $item['contactor'] = $enum_item['contactor_name'];
                                    $item['tel'] = $enum_item['tel'];
                                }else{
                                    $m_si = [
                                        'name' => $row[$i],
                                        'contactor_name' => $row[$i],
                                        'creator_id' => session('admin')['id'],
                                        'create_time' => time()
                                    ];
                                    if($si_id = $ssModel->insert($m_si,true,true)){
                                        $item[$value] = $si_id;
                                        $suppliers = db('Suppliers')->where(['id'=>['>','0']])->select();
                                    }
                                }
                                continue;
                            }else if($value == 'hire_mode'){
                                $enum_item = searchArray($this->hire_modes,'config_name',$row[$i]);
                                $item[$value] = $enum_item['id'];
                                continue;
                            }else if($value == 'hire_timelen'){
                                $enum_item = searchArray($this->hire_timelens,'',$row[$i],1);
                                $item[$value] = $enum_item['id'];
                                continue;
                            }else if($value == 'pay_mode'){
                                $enum_item = searchArray($this->pay_modes,'',$row[$i],1);
                                $item[$value] = $enum_item['id'];
                                continue;
                            }else if($value == 'pay_timelen'){
                                $enum_item = searchArray($this->pay_timelens,'',$row[$i],1);
                                $item[$value] = $enum_item['id'];
                                continue;
                            }else if($value == 'has_insurance'){
                                $item[$value] = $row[$i] == '是'?1:0;
                                continue;
                            }else if($value == 'insurance_id'){
                                $item[$value] = $row[$i];
                                if(!empty($row[$i]) && count($row[$i])>0){
                                    $insArr = [];
                                    foreach(explode(',',$row[$i]) as $ins){
                                        $enum_item = searchArray($insurances,'name',$ins);
                                        if($enum_item['id']>0){
                                            $insArr[] = $enum_item['id'];
                                        }else{
                                            $m_in = [
                                                'name' => $ins,
                                                'remark' => $ins,
                                                'amount' => 0,
                                                'creator_id' => session('admin')['id'],
                                                'create_time' => time()
                                            ];
                                            if($in_id = $inModel->insert($m_in,true,true)){
                                                $insArr[] = $in_id;
                                                $insurances = $inModel->where(['id'=>['>','0']])->select();
                                            }
                                        }
                                    }
                                    $item[$value] = $insArr;
                                }
                                continue;
                            }else if($value == 'product_date'){
                                $item[$value] = excelTime($row[$i]);
                                continue;
                            }else if($value == 'trial_date'){
                                $item[$value] = excelTime($row[$i]);
                                continue;
                            }else if($value == 'get_time'){
                                $item[$value] = excelTime($row[$i]);
                                continue;
                            }else if($value == 'start_hiretime'){
                                $item[$value] = excelTime($row[$i]);
                                continue;
                            }else if($value == 'end_hiretime'){
                                $item[$value] = excelTime($row[$i]);
                                continue;
                            }else{
                                $item[$value] = $row[$i];
                            }
                        }
                        $item['contract_files'] = [];
                        $item['cert_files'] = [];
                        if(!empty($imgs) && count($imgs)>0){
                            $contract_files = [];
                            $cert_files = [];
                            foreach($imgs as $key=>$val){
                                if($key == 'V,'.$ind){
                                    $contract = $imgs['V,'.$ind];
                                    $contract_files[] = $contract;
                                }
                                if($key == 'W,'.$ind){
                                    $cert = $imgs['W,'.$ind];
                                    $cert_files[] = $cert;
                                }
                            }
                            $item['contract_files'] = $contract_files;
                            $item['cert_files'] = $cert_files;
                        }
                        $item['creator_id'] = session('admin')['id'];
                        $item['create_time'] = time();
                        $list[] = $item;
                        $ind++;
                    }
                    if(empty($list) || count($list)<=0){
                        $json['msg'] = '文件不存在任何数据';
                        echo json_encode($json);
                        exit;
                    }
                    $count = 0;
                    $has_count = 0;
                    foreach($list as $item){
                        $data = $item;
                        if($data['product_date']){
                            $data['product_date'] = strtotime($data['product_date']);
                        }
                        if($data['trial_date']){
                            $data['trial_date'] = strtotime($data['trial_date']);
                        }
                        if($data['get_time']){
                            $data['get_time'] = strtotime($data['get_time']);
                        }
                        if(isset($data['end_hiretime'])){
                            $data['end_hiretime'] = strtotime($data['end_hiretime']);
                        }
                        if(!isset($data['next_paytime'])){
                            $len = 0;
                            $paylen = 0;
                            switch ($data['hire_timelen']) {
                                case 0:
                                $len = 1;
                                break;
                                case 1:
                                $len = 3;
                                break;
                                case 2:
                                $len = 12;
                                break;
                                case 3:
                                $len = 36;
                                break;
                            }
                            switch ($data['pay_timelen']) {
                                case 0:
                                $paylen = 1;
                                break;
                                case 1:
                                $paylen = 3;
                                break;
                                case 2:
                                $paylen = 12;
                                break;
                            }
                            $data['end_hiretime'] = 0;
                            $data['next_paytime'] = 0;
                            $start_time = $data['start_hiretime'];
                            if ($len > 0 && empty($data['end_hiretime'])) {
                                $data['end_hiretime'] = strtotime($start_time.' +'.$len.' month');
                            }
                            if ($paylen > 0) {
                                $data['next_paytime'] = strtotime($start_time.' +'.$paylen.' month');
                            }
                        }
                        if($data['start_hiretime']){
                            $data['start_hiretime'] = strtotime($data['start_hiretime']);
                        }
                        $data['customer_id'] = 0;
                        unset($data['contract_files']);
                        unset($data['cert_files']);
                        $data['insurance_id'] = 0;
                        $info = $this->model->where(['plate_no'=>$data['plate_no']])->find();
                        $insurance_ids = [];
                        $insurance_ids[] = $item['insurance_id'];
                        $contract_files = [];
                        $contract_files[] = $item['contract_files'];
                        $cert_files = [];
                        $cert_files[] = $item['cert_files'];
                        $data['businesses_id'] = $this->businesses_id;
                        if(empty($info)){
                            if($id = $this->model->insert($data,true,true)){
                                $name = date('Ymd',time()).'-'.$id;
                                $this->model->where(['id'=>$id])->update(['name'=>$name]);
                                $this->saveInsurances($id,$insurance_ids,[]);
                                $this->saveFileCar($id,$contract_files,$cert_files,[]);
                                admin_log("新增车辆信息，ID：".$id);
                                $count++;
                            }
                        }else{
                            if($this->model->where(['id'=>$info['id']])->update($data)){
                                $id = $info['id'];
                                $fileArrList = array();
                                $contractFileArrList = array();
                                $certFileArrList = array();
                                $insuranceArr = array();
                                $insuranceList = db('CarInsurance')->where(['car_id'=>$id])->select();
                                $contractFileList = db('CarFile')->where(['car_id'=>$id])->select();
                                foreach($insuranceList as $ins){
                                    $insuranceArr[] = $ins['insurance_id'];
                                }
                                foreach($contractFileList as $fitem){
                                    $fileArr = $fitem;
                                    $fileArrList[] = $fitem['file_url'];
                                    if($fitem['file_mode'] == 0){
                                        $contractFileArrList[] = $fitem;
                                        $contractFileArr[] = $fitem['file_url'];
                                    }else{
                                        $certFileArrList[] = $fitem;
                                        $certFileArr[] = $fitem['file_url'];
                                    }
                                }
                                $this->saveInsurances($id,$insurance_ids,$insuranceArr);
                                $this->saveFileCar($id,$contract_files,$cert_files,$fileArrList);
                                admin_log("更新车辆信息，ID：".$id);
                                $has_count++;
                            }
                        }
                    }
                    $json['status'] = $count>0?1:0;
                    $json['msg'] = '上传'.($count>0?'成功':'失败').',成功记录 '.$count.' 条,已存在记录 '.$has_count.' 条';
                    echo json_encode($json);
                    exit;
                }
            }
        }

        echo json_encode($json);
        exit;
    }

    /*
    * 批量删除
    */
    public function betch_del(){
        $json = [
            'status' => 0,
            'msg' => '请选择所要删除的记录'
        ];
        $car_ids = input('car_ids');
        if(!empty($car_ids) && count($car_ids)>0){
            $carIdArr = explode(',',$car_ids);
            if($this->model->where(['id'=>['in',$carIdArr]])->delete()){
                db('CarFile')->where(['car_id'=>['in',$carIdArr]])->delete();
                $json['status'] = 1;
                $json['msg'] = '删除成功';
                admin_log("删除车辆，ID：$car_ids");
            }else{
                $json['msg'] = $this->model->getError();
            }
        }

        echo json_encode($json);
        exit;
    }

    /*
    * 获取商务政策
    */
    public function ajax_amount_sum(){
        $car_id = input('car_id');
        $hire_mode = input('hire_mode');
        $sale_mode = input('sale_mode');
        $hire_timelen = input('hire_timelen');
        $timelen = 1;
        $where['car_id'] = $car_id;
        $where['hire_mode'] = $hire_mode;
        $where['sale_mode'] = $sale_mode;
        $where['hire_timelen'] = $hire_timelen;
        $json = [
            'status' => 0,
            'amount' => 0,
            'hire_amount' => 0,
            'deposit_price' => 0,
            'hire_price' => 0,
            'amount' => 0,
            'other_amount' => 0
        ];
        switch($hire_timelen){
            case 2:
            $timelen = 3;
            break;
            case 3:
            $timelen = 12;
            break;
            case 4:
            $timelen = 36;
            break;
            case 5:
            $timelen = 0;
            break;
        }

        $hireModeInfo = db('CarConfig')->where(['id'=>$hire_mode])->find();
        $info = db('CarRules')->where($where)->find();
        $deposit_price = 0;
        $hire_price = 0;
        $other_amount = 0;
        if(!empty($info) && !empty($hireModeInfo)){
            $hire_amount = 0;
            $amount = 0;
            $deposit_price = $info['deposit_price'];
            $hire_price = $info['hire_price'];
            $total_amount = $info['total_amount'];
            $other_amount = $info['other_amount'];
            switch($hireModeInfo['config_name']){
                case '以租代购':
                $hire_amount = $info['hire_price']*$timelen + $info['other_amount'];
                $amount = $info['deposit_price'] + $info['hire_price'] + $info['insurance_price'] + $info['cert_price']*$timelen;
                break;
                case '全款':
                $hire_amount = 0;                
                $amount = $info['deposit_price'] + $info['pledge_amount'] + $info['insurance_price'] + $info['poundage_amount'] + $info['transfer_amount'] + $info['gps_amount'] + $info['freight_price'];
                break;
                default:
                $hire_amount = $info['hire_price']*$timelen + $info['other_amount'];
                $amount = $info['deposit_price'] + $info['hire_price'] + $info['insurance_price'] + $info['cert_price']*$timelen;
                break;
            }
            $json['status'] = 1;
            $json['hire_amount'] = round($hire_amount,2);
            $json['deposit_price'] = round($deposit_price,2);
            $json['hire_price'] = round($hire_price,2);
            $json['total_amount'] = round($total_amount,2);
            $json['total_amount'] = round($total_amount,2);
            $json['other_amount'] = round($other_amount,2);
            $json['amount'] = round($amount,2);
        }

        echo json_encode($json);
    }
}